package com.health.mapp.service;

import java.io.IOException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.health.mapp.utils.StringUtils;
import com.health.test.TestHttpClient;

public class WeatherService {

 
		
	//http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=F5518443a55bd60bdf0fcae95ff3e664
		
		
	 

	private static Logger logger = Logger.getLogger(TestHttpClient.class);

	public static void main(String[] args) {
		WeatherService wi = new WeatherService();
		//baidu Weather interface
		String url = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=F5518443a55bd60bdf0fcae95ff3e664";
		 
		String message = "appId=12345679&version=100&method=login&timestamp=20121212154843&uuId=0e3ca914-2e4b-42aa-a65c-79390944b5a7&sign=08C3B076BF5F3A84A0649CC52D368B1A&lang=zh-Hans&fill=00000000000000000000000000000{\"memberName\":\"18908710026\",\"password\":\"1234567\"}";
		//hc.sendPostHttp(url, message);
		wi.sendGetHttp(url, message);
	}

	@SuppressWarnings("deprecation")
	public void sendPostHttp(String url, String message) {
		if (StringUtils.isBlank(message)) {
			logger.info("a blank message, return.");
			return;
		}
		logger.info(message);
	    HttpParams httpParameters = new BasicHttpParams();
	    HttpConnectionParams.setConnectionTimeout(httpParameters, 10*1000);//设置请求超时10秒
	    HttpConnectionParams.setSoTimeout(httpParameters, 10*1000); //设置等待数据超时10秒
	    HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);
	    HttpConnectionParams.setSoKeepalive(httpParameters, true);
	    
	    HttpClient httpClient = new DefaultHttpClient(httpParameters); //此时构造DefaultHttpClient时将参数传入
	    

 
 
		HttpPost post = new HttpPost(url);
		 
		 
		
		 
		//HttpEntity entity=null;
		 try {
			 //内存中开辟一块区域
//			 ByteArrayOutputStream originalContent = new ByteArrayOutputStream();
//			 originalContent.write(message.getBytes(Charset.forName("UTF-8")));
//		 
//			 //开辟第二区域
//			 ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			 //对内存字节数据输出流封装，压缩
//			 GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
//			 //完成要发送的内容压缩
//			 originalContent.writeTo(gzipOut);
//			 gzipOut.finish();
//			 
			 //那部分数据被压缩后现地放到输出流中
			// InputStream bis= new ByteArrayInputStream(baos.toByteArray());
			
			 
			// entity =new ByteArrayEntity(baos.toByteArray(),ContentType.TEXT_PLAIN );
			 
			
			 //entity= new StringEntity(message);
		 
			 StringEntity	 entity= new StringEntity(message,
					 ContentType.create("plain/text", Consts.UTF_8));
			 
			// entity.setChunked(true);
		//logger.debug(entity.getContent().toString());
		
		post.setEntity(entity);

		// String url1 = "http://www.newsmth.net/bbslogin2.php";

		// PostMethod postMethod = new PostMethod(url1);
		// postMethod.setContentChunked(true);
		// postMethod.addRequestHeader("Accept", "text/plain");
		// postMethod.setRequestHeader("Content-Encoding", "gzip");
		// postMethod.setRequestHeader("Transfer-Encoding", "chunked");
		// postMethod.setRequestBody(message);
		

		int retry = 0;

		// do {

		// int status = httpClient.executeMethod(postMethod);

		HttpResponse response = null;
		 
		 response = httpClient.execute(post);

			if (response.getStatusLine().getStatusCode() == 200) {
				logger.debug("HttpStatus成功！");
				String s;

				s = EntityUtils.toString(response.getEntity());

				logger.debug(s);
			} else {
				String s;

				s = EntityUtils.toString(response.getEntity());

				logger.debug(s);
				logger.debug("HttpStatus失败！");
			}
		 } catch (IllegalStateException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			 
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String sendGetHttp(String url, String message) {
		if (StringUtils.isBlank(message)) {
			logger.info("a blank message, return.");
			return "";
		}

		String uriAPI = "http://XXXXX?str=I+am+get+String";
		String result = "";
		// HttpGet httpRequst = new HttpGet(URI uri);
		// HttpGet httpRequst = new HttpGet(String uri);
		// 创建HttpGet或HttpPost对象，将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
		HttpGet httpRequst = new HttpGet(url);

		// new DefaultHttpClient().execute(HttpUriRequst requst);
		try {
			// 使用DefaultHttpClient类的execute方法发送HTTP GET请求，并返回HttpResponse对象。
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequst);// 其中HttpGet是HttpUriRequst的子类
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity httpEntity = httpResponse.getEntity();
				result = EntityUtils.toString(httpEntity);// 取出应答字符串
				// 一般来说都要删除多余的字符
				result.replaceAll("\r", "");// 去掉返回结果中的"\r"字符，否则会在结果字符串后面显示一个小方格
			} 
			else
			{
				httpRequst.abort();
			}
			//logger.debug("result:"+result);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = e.getMessage().toString();
		}
		
		return result;

	}


}
